import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { fetchCartPostSlice, IBall, IResponse } from './cart.actions';
import { loadStorage } from '../storage';


export const CART_STORAGE = 'cartData';

interface IBalls {
  balls: IBall[];
  loading: boolean;
  errors: null;
  success: boolean;
}

const initialState: IBalls = loadStorage(CART_STORAGE) ?? {
	balls:  [],
	loading: false,
	errors: null,
	success: false
};

export const cartSlice = createSlice({
	name: 'cart',
	initialState,
	reducers: {
		addBallToCart: (state, action) => {
			state.balls = [...state.balls, action.payload];
		},
		deleteBallOnCart: (state, action: PayloadAction<number>) => {
			state.balls = state.balls.filter(item => item.id !== action.payload);
		},
		incrementCount: (state, action: PayloadAction<number>) => {
			state.balls = state.balls.map(item => item.id === action.payload ? ({...item, count: item.count+1 }) : item);
		},
		decrementCount: (state, action) => {
			state.balls = state.balls.map(item => item.id === action.payload && item.count !== 1 ? ({...item, count: item.count-1 }) : item);
		},
		clearCart: (state) => {
			state.balls = [];
		}
	},
	extraReducers: (builder) => {
		builder.addCase(fetchCartPostSlice.pending, (state) => {
			state.loading = true;
			state.errors = null;
		});
		builder.addCase(
			fetchCartPostSlice.fulfilled,
			(state, action: PayloadAction<IResponse>) => {
				// if (!action.payload) {
				// 	state.balls.push(action.payload);
				// }
				state.loading = false;
			}
		);
		builder.addCase(fetchCartPostSlice.rejected, (state, action) => {
			// state.loading = true;
			state.errors = action.error.message;
		});
	}
});

export default cartSlice.reducer;
export const { addBallToCart, deleteBallOnCart, incrementCount, decrementCount, clearCart } = cartSlice.actions;
